package com.hoyue.system.controller;

import com.hoyue.common.utils.ShiroSessionUtils;
import com.hoyue.common.utils.ShiroUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 空白
 * @version 1.0
 * Create by 2019/08/08 01:32
 */
@Controller
@RequestMapping("")
public class LoginController {

    @PostMapping("/login")
    public String login(Model model, String email, String password) {
        // 获取当前的Subject.调用SecurityUtils.getSubject()
        Subject subject = ShiroUtils.getSubjct();
        // 把邮箱和密码封装成email、PasswordToken对象
        UsernamePasswordToken token = new UsernamePasswordToken(email, password);
        try {
            // 执行登录，login()方法会把token值传入到realm里
            subject.login(token);
            ShiroSessionUtils.setShiroAttribute("currentUser", subject);
            // 重定向到课堂主页页面
            return "redirect:course/list";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("errorInfo", "用户名错误");
            return "login";
        }
    }
}
